package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.persist.PhotoHelper;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 本地图片分类
 * @author shawn
 *
 */
public class PhotoLocalCategory extends Activity
{
	private static final int ICON_WIDTH = 64;
	private static final int ICON_HEIGHT = 64;
	private float scaleRatio;
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final int REFRESHED = 1;//更新已完成事件
	private YoumiManager youmi = new YoumiManager(this);
	private PhotoHelper photoHelper = new PhotoHelper(this);
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			//	更新事件处理
			if(msg.what == REFRESHED)
			{
				LinearLayout layout = (LinearLayout) findViewById(R.id.photoLocalCategoryLayout);
				layout.removeAllViews();

				List<PhotoHelper.PhotoCategory> list = photoHelper.getCategoryList();
				for(PhotoHelper.PhotoCategory cate : list)
				{
					showView(layout, cate);
				}
				ScrollView scroll = (ScrollView) findViewById(R.id.photoLocalCategoryScroll);
				scroll.scrollTo(0, 0);

				//	显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 30)
				{
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE, Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}

		//	显示列表视图中的一个元素
		private void showView(LinearLayout layout, final PhotoHelper.PhotoCategory theCategory)
		{
			//	首先是一个横向的布局
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0f);
			params.gravity = 0x30;
			LinearLayout item = new LinearLayout(PhotoLocalCategory.this);
			item.setOrientation(LinearLayout.HORIZONTAL);
			item.setLayoutParams(params);
			layout.addView(item);
			item.setClickable(true);
			item.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					//	设置点击事件，显示指定类型下的图片缩略图
					Bundle extras = new Bundle();
					extras.putInt(PhotoLocalList.PHOTO_CATEGORY_ID, theCategory.id);
					extras.putString(PhotoLocalList.PHOTO_CATEGORY_NAME, theCategory.name);
					Intent photoListIntent = new Intent();
					photoListIntent.setClass(PhotoLocalCategory.this, PhotoLocalList.class);
					photoListIntent.putExtras(extras);
					startActivity(photoListIntent);
				}
			});
			item.setOnTouchListener(new OnTouchListener()
			{
				@Override
				public boolean onTouch(View view, MotionEvent motionevent)
				{
					LinearLayout layout = (LinearLayout) view;
					int action = motionevent.getAction();
					if(action == MotionEvent.ACTION_DOWN)
					{
						layout.setBackgroundColor(Color.GREEN);
					}
					else if(action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_OUTSIDE)
					{
						layout.setBackgroundColor(Color.TRANSPARENT);
					}

					return false;
				}
			});

			//	图片
			InputStream is = null;
			try
			{
				String path = AddressConstant.PHOTO_CATEGORY_IMAGE_LOCAL.replace("ID", theCategory.id + "");
				File file = new File(path);
				if(file.exists())
				{
					is = new FileInputStream(file);
				}
				else
				{
					//	本地图片丢了的情况
					is = getResources().openRawResource(R.raw.icon_failed);
				}
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				ImageView imageView = new ImageView(PhotoLocalCategory.this);
				imageView.setImageBitmap(bitmap);
				imageView.setMaxWidth((int) (ICON_WIDTH * scaleRatio));
				imageView.setMaxHeight((int) (ICON_HEIGHT * scaleRatio));
				imageView.setMinimumWidth((int) (ICON_WIDTH * scaleRatio));
				imageView.setMinimumHeight((int) (ICON_HEIGHT * scaleRatio));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				item.addView(imageView);
			}
			catch(Exception e)
			{
				Log.d(this.getClass().getName(), "", e);
			}
			finally
			{
				if(is != null)
				{
					try { is.close(); } catch (Exception e) { };
				}
			}

			//	右边一个上下结构的布局
			params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0f);
			params.gravity = 0x03 | 0x30;
			LinearLayout itemRight = new LinearLayout(PhotoLocalCategory.this);
			itemRight.setPadding(5, 0, 0, 0);
			itemRight.setOrientation(LinearLayout.VERTICAL);
			itemRight.setLayoutParams(params);
			item.addView(itemRight);

			//	右上方名称
			TextView nameView = new TextView(PhotoLocalCategory.this);
			nameView.setText(theCategory.name);
			nameView.setGravity(0x03 | 0x30);
			nameView.setTextColor(Color.BLACK);
			nameView.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
			itemRight.addView(nameView);

			//	右侧更新时间
			TextView updateView = new TextView(PhotoLocalCategory.this);
			updateView.setText(sdf.format(theCategory.update));
			updateView.setGravity(0x03 | 0x30);
			updateView.setTextColor(Color.BLACK);
			updateView.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
			itemRight.addView(updateView);

			//	右下方简介
			TextView summary = new TextView(PhotoLocalCategory.this);
			summary.setText(theCategory.description);
			summary.setGravity(0x03 | 0x30);
			summary.setTextColor(0xAA000000);
			itemRight.addView(summary);

			//	最后再显示一个条分割线比较好
			ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 3);
			TextView seperator = new TextView(PhotoLocalCategory.this);
			seperator.setBackgroundColor(0x88888888);
			seperator.setLayoutParams(layoutParams);
			layout.addView(seperator);
		}
	};

	@Override
    public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_local_category);
		onUpdateClicked(null);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		scaleRatio = dm.density;
	}

	/**
	 * 刷新
	 * @param v
	 */
	public void onUpdateClicked(View v)
	{
		Message msg = new Message();
		msg.what = REFRESHED;
		handler.sendMessage(msg);
	}

	/**
	 * 返回
	 * @param v
	 */
	public void onExitClicked(View v)
	{
		finish();
	}
}
